package online.flowerinsnow.minecraft.bukkit.floweress.message

import online.flowerinsnow.minecraft.bukkit.floweress.FlowerEss
import online.flowerinsnow.minecraft.bukkit.floweress.util.MessageUtils
import org.bukkit.configuration.file.YamlConfiguration
import java.io.File
import java.io.InputStreamReader
import java.lang.StringBuilder

enum class MessageConfig(val key : String) {
    NOPERMISSION("nopermission"),
    CONSOLE("console"),
    TARGETNOTONLINE("targetnotonline"),

    FLY_USAGE("fly.usage"),
    FLY_ENABLE_SELF("fly.enable.self"),
    FLY_ENABLE_OTHER("fly.enable.other"),
    FLY_DISABLE_SELF("fly.disable.self"),
    FLY_DISABLE_OTHER("fly.disable.other"),

    FAC_USAGE("fac.usage"),
    FAC_FACKICK_BROADCAST("fac.fackick.broadcast"),
    FAC_FACKICK_KICK("fac.fackick.kick"),
    FAC_NOTIFY_I("fac.notify.I"),
    FAC_NOTIFY_II("fac.notify.II"),
    FAC_OWKICK_BROADCAST("fac.owkick.broadcast"),
    FAC_OWKICK_KICK("fac.owkick.kick"),

    VISIBLE_USAGE("visible.usage"),
    VISIBLE_ENABLE_SELF("visible.enable.self"),
    VISIBLE_ENABLE_OTHER("visible.enable.other"),
    VISIBLE_DISABLE_SELF("visible.disable.self"),
    VISIBLE_DISABLE_OTHER("visible.disable.other")
    ;

    fun getMessage() : String {
        return when {
            config.isString(key) -> {
                MessageUtils.parseColor(config.getString(key)!!)
            }
            config.isList(key) -> {
                MessageUtils.parseColor(getMultilineMessage())
            }
            else -> ""
        }
    }

    private fun getMultilineMessage() : String {
        val list = config.getStringList(key)
        val sb = StringBuilder()
        for (i in 0 until list.size) {
            sb.append(list[i])
            if (i + 1 < list.size) sb.append("\n")
        }
        return sb.toString()
    }

    companion object {
        lateinit var config : YamlConfiguration
            private set

        fun saveDefaultConfig() {
            val file = File(FlowerEss.instance.dataFolder, "messages.yml")
            if (!file.exists()) {
                FlowerEss.instance.saveResource("messages.yml", false)
            }
        }

        fun reloadConfig() {
            val file = File(FlowerEss.instance.dataFolder, "messages.yml")
            config = YamlConfiguration.loadConfiguration(file)
            val default = YamlConfiguration.loadConfiguration(InputStreamReader(FlowerEss.instance.getResource("messages.yml")!!))
            config.setDefaults(default)
            config.save(file)
        }
    }
}